package com.ztao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.admin.pojos.ApUserRealname;
import com.heima.model.common.admin.dto.AuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.user.dto.LoginDto;
import com.heima.model.common.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.ztao.mapper.ApUserRealnameMapper;
import com.ztao.mapper.UserMapper;
import com.ztao.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public ResponseResult login(LoginDto dto) {
        if(!StringUtils.isBlank(dto.getPhone())&&!StringUtils.isBlank(dto.getPassword())){
            QueryWrapper<ApUser> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(ApUser::getPhone,dto.getPhone());
            ApUser apUser = this.userMapper.selectOne(queryWrapper);
            if(apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            String pwd=apUser.getSalt();
            String pwd1=dto.getPassword();
            pwd1= DigestUtils.md5DigestAsHex((pwd1+pwd).getBytes());
            if(!pwd1.equals(apUser.getPassword())){
               return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            Map<String,Object> map=new HashMap<>();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt(null);
            apUser.setPassword(null);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            Map<String,Object> map=new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

    }
    private static final String CHARACHTERs="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    @Override
    public ResponseResult  register(ApUser apUser) {
        ApUser apUser1 = this.userMapper.selectOne(new QueryWrapper<ApUser>().eq("phone", apUser.getPhone()));
        if(apUser1!=null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"手机号已存在");
        }
        Random random=new Random();
        StringBuilder salt=new StringBuilder();
        for (int i=0;i<3;i++){
            int i1 = random.nextInt(CHARACHTERs.length());
            char c = CHARACHTERs.charAt(i1);
            salt.append(c);
        }
        apUser.setSalt(salt.toString());
        apUser.setPassword(DigestUtils.md5DigestAsHex((apUser.getPassword()+apUser.getSalt()).getBytes()));
        apUser.setCreatedTime(LocalDateTime.now());
        apUser.setStatus(true);
        this.userMapper.insert(apUser);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Resource
    private ApUserRealnameMapper apUserRealnameMapper;
    @Override
    public ResponseResult findAll_realname(AuthDto dto) {
        IPage<ApUserRealname> page=new Page<>(dto.getPage(),dto.getSize());
        QueryWrapper<ApUserRealname> queryWrapper=new QueryWrapper<>();
        if(dto.getStatus()!=null){
            queryWrapper.lambda().eq(ApUserRealname::getStatus,dto.getStatus());
        }
        page=this.apUserRealnameMapper.selectPage(page,queryWrapper);
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        result.setData(page.getRecords());
        return  result;
    }

    //认证失败
    @Override
    public ResponseResult authFail(AuthDto dto) {
        ApUserRealname apUserRealname = this.apUserRealnameMapper.selectById(dto.getId());
        if(apUserRealname.getStatus()==1){
            apUserRealname.setStatus(2);
            apUserRealname.setReason(dto.getMsg());
            this.apUserRealnameMapper.updateById(apUserRealname);
        }
        return ResponseResult.errorResult(500,"认证失败"+dto.getMsg());
    }
    //认证成功
    @Override
    public ResponseResult authSuccess(AuthDto dto) {
        ApUserRealname apUserRealname = this.apUserRealnameMapper.selectById(dto.getId());
        if(apUserRealname.getStatus()==1){
            apUserRealname.setStatus(9);
            this.apUserRealnameMapper.updateById(apUserRealname);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
